package com.zimin.cloud.file.biz.impl;

import com.zimin.cloud.file.biz.IFileUploadBiz;
import com.zimin.cloud.file.pojo.entity.FileMapping;
import com.zimin.cloud.file.repository.IFileMappingRepository;
import com.zimin.cloud.file.resource.FileResource;
import com.zimin.cloud.file.service.IFileUploadService;
import com.zimin.common.annotation.Biz;
import com.zimin.common.constant.FileConstant;
import com.zimin.common.exception.GraceException;
import com.zimin.common.utils.Md5Util;
import com.zimin.common.utils.ObjectUtils;
import com.zimin.shared.enums.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zimin
 * @since 2022/3/30 10:28 上午
 */
@Biz(value = "fileUploadBiz")
@Slf4j
public class FileUploadBizImpl implements IFileUploadBiz {
    @Autowired
    private FileResource fileResource;
    @Autowired
    private IFileUploadService fileUploadService;
    @Autowired
    private IFileMappingRepository fileMappingRepository;

    @Override
    public String uploadImage(MultipartFile file) throws Exception {
        var unique = Md5Util.getFileMD5(file);
        var fileMapping = fileMappingRepository.findByUnique(unique);
        if (ObjectUtils.isNotEmpty(fileMapping)) {
            return fileMapping.getPath();
        }
        GraceException.isNull(file, ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        //获取文件上传名称
        var fileName = file.getOriginalFilename();
        //判断文件名不能为空
        GraceException.isNull(fileName, ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        var fileNameArr = fileName.split("\\.");
        //获得后缀
        var suffix = fileNameArr[fileNameArr.length - 1];
        //判断后缀符合我们的预定义的规范
        GraceException.isFalse(FileConstant.IMAGE_TYPE.contains(suffix),ResponseStatusEnum.FILE_FORMATTER_FAIL);
        var path = fileUploadService.uploadOSS(file, suffix);
        //上传文件路径为空
        GraceException.isNull(path, ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        var finalPath = fileResource.getOssHost() + path;
        log.info("path:{}", finalPath);
        fileMapping = new FileMapping(Sid.next(), unique, finalPath);
        fileMappingRepository.insert(fileMapping);
        //上传成功后保存路径到数据库中
        return finalPath;
    }
}
